package org.example.redisexamples.service;

import lombok.Builder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.redisexamples.component.ULID;
import org.example.redisexamples.dto.Item;
import org.example.redisexamples.dto.Order;
import org.redisson.api.*;
import org.redisson.api.stream.StreamAddArgs;
import org.redisson.client.codec.IntegerCodec;
import org.redisson.client.codec.StringCodec;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderService {

    private final RedissonClient Client;
    private final ULID ULID;

    public void addItem(List<Item> items) {
        RBatch batch =Client.createBatch();
        for (Item item : items) {
//
//          batch.getMap()方法来获取一个异步的RMap对象
            RMapAsync<String,Integer> map =batch.getMap(Item.PRE_KRY+item.getId(), IntegerCodec.INSTANCE);
            map.putAsync("total",item.getTotal());
        }
        batch.execute(); //统一进行批处理操作
    }

    public long buy(String itemId, String userId) {
        long q = Client.getFunction().call(FunctionMode.WRITE,
                "buy_6", FunctionResult.LONG, List.of(Item.PRE_KRY + itemId));
//        抢完了
        if (q == -1) {
            log.debug("抢光了！");
            return -1;
        }
        var id = ULID.nextULID();
        Order o = Order.builder()
                .id(id)
                .userId(userId)
                .itemId(itemId)
                .build();
        Client.getBucket(Order.PRE_KEY + id).set(o);
        sendMessage(o);
        return q;
    }


    public void sendMessage(Order order){
        Client.getStream(Order.STREAM_KEY, StringCodec.INSTANCE)
                .add(StreamAddArgs.entry("orderid",order.getId()));
    }


}
